﻿using Newtonsoft.Json;

namespace IOCDemo.IocVersion2;

public class Container:IContainer
{
    private IServiceCollection _services;

    public Container(IServiceCollection services)
    {
        _services = services;
    }

    public TService GetService<TService>(string tag = "")
    {
        return CastInstance<TService>(_services[typeof(TService).Name+tag].GetService());
    }

    public TService Resovle<TService>(string tag = "")
    {
        return GetService<TService>();
    }
    /// <summary>
    /// 转换类型
    /// </summary>
    /// <typeparam name="TService"></typeparam>
    /// <returns></returns>
    public static TService CastInstance<TService>(object instance)
    {
        try
        {
            return (TService)instance;
        }
        catch (InvalidCastException exception)
        {
            return default(TService);
        }
    }
}